/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hanze.shoestring.dao.impl;

import java.util.*;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import nl.hanze.shoestring.dao.PlanningDAO;
import nl.hanze.shoestring.domain.*;

/**
 *
 * @author alex
 */
public class PlanningDAOImpl extends BaseDAOImpl<Planning> implements PlanningDAO {

    public PlanningDAOImpl() {
    }

    @Override
    public List<Planning> find(String name, Date startDate, Date endDate) {
        boolean hasName = name != null && name.length() > 0;
        boolean hasStartDate = startDate != null;
        boolean hasEndDate = endDate != null;

        List<Predicate> prList = new ArrayList<>();

        open();

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Planning> query = cb.createQuery(Planning.class);
        Root<Planning> from = query.from(Planning.class);
        Join<Planning, Reis> reis = from.join(Planning_.reisId);

        if (hasStartDate && hasEndDate) {
            prList.add(cb.between(from.get(Planning_.datumVan), startDate, endDate));
        } else if (hasStartDate) {
            prList.add(cb.greaterThan(from.get(Planning_.datumVan), startDate));
        } else if (hasEndDate) {
            prList.add(cb.lessThan(from.get(Planning_.datumVan), endDate));
        }

        if (hasName) {
            prList.add(cb.like(reis.get(Reis_.naam),"%" + name + "%"));
        }


        Predicate[] p = new Predicate[prList.size()];
        prList.toArray(p);

        query.where(p);

        TypedQuery<Planning> typedQuery = em.createQuery(query);
        return typedQuery.getResultList();
    }
}
